package com.wangsd.web.controller;

import com.wangsd.core.entity.JSONResult;
import com.wangsd.core.util.DateUtils;
import com.wangsd.core.util.StaticVar;
import com.wangsd.web.model.Billaccount;
import com.wangsd.web.model.Housinginfo;
import com.wangsd.web.model.Watermeter;
import com.wangsd.web.modelCustom.DataTable;
import com.wangsd.web.modelCustom.ParentCustom;
import com.wangsd.web.modelCustom.UserCustom;
import com.wangsd.web.modelCustom.WatermeterCustom;
import com.wangsd.web.service.BillAccountService;
import com.wangsd.web.service.HousinginfoService;
import com.wangsd.web.service.RoominfoService;
import com.wangsd.web.service.WatermeterService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * Created by wangsd on 2017-12-11.
 */
@Controller
@RequestMapping("/watermeter")
public class WatermeterController {

    @Autowired
    RoominfoService roominfoService;
    @Autowired
    HousinginfoService housinginfoService;
    @Autowired
    WatermeterService watermeterService;
    @Autowired
    BillAccountService billAccountService;

    @RequestMapping("/watermeterList")
    public String watermeterList(HttpServletRequest request, Model model,WatermeterCustom watermeter) {   	
    	return "/watermeter/watermeter-list";
    }
    
    /**
     * 
     * Description: 分页显示
     * @param request
     * @param model
     * @param watermeter
     * @return
     */
    @RequestMapping("/watermeterListNew")
    @ResponseBody
    public DataTable watermeterListNew(HttpServletRequest request, Model model,WatermeterCustom watermeter) {
    	DataTable table = new DataTable();
    	UserCustom loginUser = (UserCustom) request.getSession().getAttribute("userInfo");
        String parentCode = loginUser.getParentCode();
        watermeter.setHousingcode(parentCode);
    	List<WatermeterCustom> watermeterList1=watermeterService.selectAllWatermeterInfo(watermeter);
    	watermeter.setStart(null);
    	watermeter.setLength(null);
    	List<WatermeterCustom> watermeterList2=watermeterService.selectAllWatermeterInfo(watermeter);
    	//model.addAttribute("watermeterList", watermeterList);
    	int num=watermeterList2.size();
    	table.setRecordsFiltered(num);
        table.setRecordsTotal(num);
        table.setData(watermeterList1);
    	//return "/watermeter/watermeter-list";
        return table;
    }

    @RequestMapping("/openWatermeter")
    public String openWatermeter(HttpServletRequest request, Model model) {
        UserCustom loginUser = (UserCustom) request.getSession().getAttribute("userInfo");
        int parentId=loginUser.getParentId();
        Housinginfo housinginfo=housinginfoService.selectHousinginfoById(parentId);
        model.addAttribute("housinginfo", housinginfo);
        List<ParentCustom> roomlist = roominfoService.queryParentRoomById(parentId);
        model.addAttribute("roomlist", roomlist);              
        return "/watermeter/watermeter-info";
    }
    
    /**
     * 
     * Description: 抄表
     * @param request
     * @param model
     * @return
     */
    @SuppressWarnings("rawtypes")
	@RequestMapping("/saveOrUpdateWatermeter")
    @ResponseBody
    public JSONResult saveOrUpdateWatermeter(HttpServletRequest request, Model model,Watermeter watermeter) {
    	JSONResult obj = new JSONResult();
    	WatermeterCustom watermeterNew1=new WatermeterCustom();
    	watermeterNew1.setRoominfoId(watermeter.getRoominfoId());
    	String date1=DateUtils.getCurDate();
    	watermeterNew1.setCreateTimeStr(date1);
    	Watermeter watermeterNew2=watermeterService.selectWatermeterInfobyRoomId(watermeterNew1);
    	if(watermeterNew2!=null){
    		obj.setSuccess(false);
    		obj.setMessage("本月水表该房间只能抄一次");
    		return obj;
    	}   	
    	UserCustom loginUser = (UserCustom) request.getSession().getAttribute("userInfo");
        int id=loginUser.getId();
        watermeter.setUserId(id);
        Double useNum=watermeter.getWaterNum()-watermeter.getOldWaterNum();
        watermeter.setUseNum(useNum);
        //得到小区水费单价
        Housinginfo housinginfo=housinginfoService.selectHousinginfoById(watermeter.getHousingId());        
        Double waterUnit=housinginfo.getWaterUnit();
        Double amount=0.0;
        if(waterUnit!=null&&waterUnit!=0.0){
        	amount=useNum*waterUnit;
        }else{
        	amount=useNum*StaticVar.WATER_UNIT;
        }   
        watermeter.setAmount(amount);
        watermeter.setCreateTime(new Date());
        watermeter.setOldUseNum(0.0);
        //得到上一次的水表实数和用量
        Watermeter watermeterNew=watermeterService.selectOldWatermeterInfo(watermeter.getRoominfoId());
        if(watermeterNew!=null){
        	watermeter.setOldUseNum(watermeterNew.getUseNum());
            watermeter.setOldWaterNum(watermeterNew.getWaterNum());
        } 
        watermeter.setStatus(false);
        boolean result=watermeterService.insertWatermeter(watermeter);       
        obj.setSuccess(result);
        if(result){
        	obj.setMessage("提交成功");
        }else{
        	obj.setMessage("提交失败");
        }
        return obj;
    }
    
    /**
     * 
     * Description: 获取房间主人信息
     * @param request
     * @param model
     * @return
     */
	@RequestMapping("/queryOwnerByRoomId")
    @ResponseBody
    public WatermeterCustom queryOwnerByRoomId(HttpServletRequest request, Model model,int roomId) {
		WatermeterCustom watermeterCustom=watermeterService.selectRoomAndWatermeterInfo(roomId);
		Double waterNum=watermeterCustom.getWaterNum();
		if(waterNum==null||waterNum==0.0){
			watermeterCustom.setWaterNum(0.0);
		}
		return watermeterCustom;
    }
	
	/**
	 * 
	 * Description: 跳转修改水表信息
	 * @param request
	 * @param model
	 * @param id
	 * @return
	 */
	@RequestMapping("/goUpdateWatermeter")
    public String goUpdateWatermeter(HttpServletRequest request,WatermeterCustom watermeter, Model model,int id) {
		UserCustom loginUser = (UserCustom) request.getSession().getAttribute("userInfo");
        String parentCode = loginUser.getParentCode();
        watermeter.setHousingcode(parentCode);
		watermeter.setId(id);
		WatermeterCustom watermeterList=watermeterService.selectAllWatermeterInfo(watermeter).get(0);
		model.addAttribute("watermeterList", watermeterList);
		return "/watermeter/watermeter-edit";
    }
	
	/**
	 * 
	 * Description: 修改水表信息
	 * @param watermeter
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	@RequestMapping("/updateWatermeter")
	@ResponseBody
    public JSONResult updateWatermeter(Watermeter watermeter) {
		JSONResult obj = new JSONResult();
		Double useNum=watermeter.getWaterNum()-watermeter.getOldWaterNum();
        watermeter.setUseNum(useNum);
		//得到小区水费单价
        Housinginfo housinginfo=housinginfoService.selectHousinginfoById(watermeter.getHousingId());        
        Double waterUnit=housinginfo.getWaterUnit();
        Double amount=0.0;
        if(waterUnit!=null&&waterUnit!=0.0){
        	amount=useNum*waterUnit;
        }else{
        	amount=useNum*StaticVar.WATER_UNIT;
        }
        watermeter.setAmount(amount);
	    boolean result=watermeterService.updateWatermeter(watermeter);
		obj.setSuccess(result);
        if(result){
        	obj.setMessage("修改成功");
        }else{
        	obj.setMessage("修改失败");
        }
		return obj;
    }
	
	/**
	 * 
	 * Description: 上传账单
	 * @param
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	@RequestMapping("/infoUpload")
	@ResponseBody
    public JSONResult infoUpload(Integer[] ids) {
		JSONResult obj = new JSONResult();		
		boolean result=false;
		for (int i = 0; i < ids.length; i++) {
			Billaccount billaccount=new Billaccount();
			Watermeter watermeterNew=watermeterService.selectByPrimaryKey(ids[i]);
			if(watermeterNew.getStatus()==false){
				billaccount.setHousingId(watermeterNew.getHousingId());
				billaccount.setCostType(9);
				billaccount.setRoominfoId(watermeterNew.getRoominfoId());		
				billaccount.setBillEntryAmount(watermeterNew.getAmount());
				Date date=watermeterNew.getCreateTime();
				billaccount.setAcctPeriod(watermeterNew.getOldWaterNum() + "-" + watermeterNew.getWaterNum());
				billaccount.setReleaseDay(DateUtils.formatDate(date, "yyyyMMdd"));
				//String deadline=DateUtils.monthByDate(date,1);
				billaccount.setDeadline("20201231");
				billaccount.setCreateTime(new Date());
				result=billAccountService.insertBillaccount(billaccount);			
				if(result){
			        watermeterNew.setStatus(true);
			        watermeterService.updateWatermeter(watermeterNew);
			    }
			}			
		}
		obj.setSuccess(result);
        if(result){        	
        	obj.setMessage("上传账单成功");
        }else{
        	obj.setMessage("上传账单失败");
        }
		return obj;
    }
	
	/**
	 * 
	 * Description: 导出表格
	 * @param
	 * @param request
	 * @param model
	 * @param response
	 */
	@RequestMapping("/downloadWatermeterList")
	public void downloadInvoiceList(WatermeterCustom record, HttpServletRequest request, Model model, HttpServletResponse response) {      
		UserCustom loginUser = (UserCustom) request.getSession().getAttribute("userInfo");
        String parentCode = loginUser.getParentCode();
        record.setHousingcode(parentCode);
		HSSFWorkbook workbook = watermeterService.exportWatermeterInfo(record);
        HttpServletResponse httpResponse = response;
        httpResponse.setCharacterEncoding("UTF-8");
        httpResponse.setHeader("Content-Disposition ", "attachment; filename=downloadWatermeterList.xls");
        httpResponse.setContentType("application/vnd.ms-excel");
        try {
            ServletOutputStream outputStream = httpResponse.getOutputStream();
            workbook.write(outputStream);
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
	
	/**
	 * 
	 * Description: 批量删除
	 * @param ids
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	@RequestMapping("/listDel")
	@ResponseBody
	public JSONResult listDel(Integer[] ids) {
		JSONResult obj = new JSONResult();		
		boolean result=false;
		for (int i = 0; i < ids.length; i++) {
			int num=watermeterService.deleteWatermeterInfo(ids[i]);
			if(num==1){
				result=true;
			}
		}
		obj.setSuccess(result);
        if(result){        	
        	obj.setMessage("删除成功");
        }else{
        	obj.setMessage("删除失败");
        }
		return obj;
    }
}
